#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <linux/can.h>
#include <linux/can/raw.h>

#define CAN_INTERFACE "can0"  // 设置CAN接口名称
#define NUM_FRAMES 3         // 要发送和接收的数据帧数

int main() {
    int sock;
    struct sockaddr_can addr;
    struct can_frame frame;
    struct ifreq ifr;

    // 创建原始套接字
    sock = socket(PF_CAN, SOCK_RAW, CAN_RAW);
    if (sock < 0) {
        perror("Error opening socket");
        return -1;
    }

    // 设置CAN接口
    strncpy(ifr.ifr_name, CAN_INTERFACE, IFNAMSIZ);
    if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0) {
        perror("Error getting interface index");
        return -1;
    }

    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;

    // 绑定套接字
    if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
        perror("Error binding socket");
        return -1;
    }

    // 发送 3 个数据帧
    for (int i = 0; i < NUM_FRAMES; i++) {
        frame.can_id = 0x123 + i;  // 设置帧 ID（示例）
        frame.can_dlc = 8;         // 设置数据长度（最大为 8 字节）
        
        // 设置数据内容
        for (int j = 0; j < frame.can_dlc; j++) {
            frame.data[j] = (i + 1) * (j + 1);  // 填充数据
        }

        if (write(sock, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
            perror("Error sending CAN frame");
            return -1;
        }

        printf("Sent CAN frame %d with ID 0x%X\n", i + 1, frame.can_id);
    }

    // 接收 3 个数据帧
    for (int i = 0; i < NUM_FRAMES; i++) {
        if (read(sock, &frame, sizeof(struct can_frame)) < 0) {
            perror("Error receiving CAN frame");
            return -1;
        }

        printf("Received CAN frame %d with ID 0x%X\n", i + 1, frame.can_id);
        printf("Data: ");
        for (int j = 0; j < frame.can_dlc; j++) {
            printf("%02X ", frame.data[j]);
        }
        printf("\n");
    }

    // 关闭套接字
    close(sock);
    return 0;
}

